package com.zx.idc.backend.gui.api.management.infosecurity.activeresources.base.impl;

import com.zx.idc.backend.gui.api.management.infosecurity.activeresources.base.pojo.ReportDate;
import com.zx.idc.common.lang.ListUtil;
import com.zx.idc.common.spring.SpringConfigUtil;
import com.zx.idc.common.util.JsonUtil;
import com.zx.idc.common.util.LocalDateTimeFormatUtil;
import com.zx.idc.ds.base.house.entity.BaseHouseInfo;
import com.zx.idc.ds.base.house.service.IBaseHouseInfoService;
import com.zx.idc.ds.base.oper.service.IBaseOperCompanyService;
import com.zx.idc.ds.upload.vo.UploadHotUrlVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.zx.idc.common.attributes.SystemAttributes.WEB_SERVICE_FIND_URL_LIST_DIR;
import static org.apache.commons.io.FileUtils.readLines;

@Service
@Transactional(rollbackFor = Exception.class)
public class FindUrlListServiceImpl {

    private final Logger log = LoggerFactory.getLogger(FindUrlListServiceImpl.class);
    private static final String FILE_SUFFIX = ".txt";

    @Autowired
    private IBaseHouseInfoService iBaseHouseInfoService;

    @Autowired
    private IBaseOperCompanyService iBaseOperCompanyService;

    /**
     * 获取上报的数据
     */
    public ReportDate<UploadHotUrlVo> getReportDate() {
        log.debug("active url report start！");
        List<String> urlFilePaths = getUrlFilePaths();
        List<UploadHotUrlVo> lists = new ArrayList<>();
        if (ListUtil.isNotEmpty(urlFilePaths)) {
            for (String path : urlFilePaths) {
                try {
                    //读出所有内容
                    List<String> strings = readLines(new File(path), StandardCharsets.UTF_8);
                    String[] split = path.split("/");
                    String houseId = split[split.length - 2];
                    lists.addAll(dataConversion(strings, houseId));
                } catch (IOException e) {
                    log.error("活跃资源上报读出文件错误:{}", e.getMessage());
                }
            }
        }
        log.debug("active url report done！");
        return new ReportDate<UploadHotUrlVo>()
            .setData(lists)
            .setFilePaths(urlFilePaths);
    }

    private List<UploadHotUrlVo> dataConversion(List<String> data, String houseId) {
        return data.stream().map(jsonString ->
            {
                UploadHotUrlVo uploadHotUrlVo = JsonUtil.read(jsonString, UploadHotUrlVo.class);
                if (uploadHotUrlVo != null) {
                    uploadHotUrlVo.setHouseId(houseId);
                }
                return uploadHotUrlVo;
            }
        ).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 所有机房下的活跃url上报文件的路径
     * 文件名:{hot url root dir}/{houseId}/{yyyyMMddHH}.txt
     * yyyyMMddHH
     *
     * @return
     */
    private List<String> getUrlFilePaths() {
        //根目录
        String hotUrlRootDir = SpringConfigUtil.get(WEB_SERVICE_FIND_URL_LIST_DIR);
        String lastHour = getLastHour();
        String idcId = iBaseOperCompanyService.getIdcId();
        List<BaseHouseInfo> baseHouseInfos = iBaseHouseInfoService.selectList(new BaseHouseInfo().setIdcId(idcId));
        return baseHouseInfos.stream().map(baseHouseInfo ->
            new StringBuilder()
                .append(hotUrlRootDir)
                .append("/")
                .append(baseHouseInfo.getId())
                .append("/")
                .append(lastHour)
                .append(FILE_SUFFIX)
                .toString()
        ).collect(Collectors.toList());
    }

    /**
     * 获取上一小时的字符串 格式{yyyyMMddHH}
     *
     * @return 获取上一小时的字符串 格式{yyyyMMddHH}
     */
    private String getLastHour() {
        return LocalDateTimeFormatUtil.formatLocalDateTime(LocalDateTime.now().minusHours(1), "yyyyMMddHH");
    }
}
